<!-- 文件路径: src/components/TaskPeopleDisplay.vue -->
<template>
  <div class="task-people-display">
    <!-- 人员信息显示面板 -->
    <div class="people-info-panel" v-if="showInfoPanel">
      <h3>任务人员 ({{ flattenedPeople.length }})</h3>
      <div class="people-list">
        <div 
          v-for="(person, index) in flattenedPeople" 
          :key="index" 
          class="person-item"
          :class="{ 'active': activePersonIndex === index }"
          @click="focusOnPerson(person)"
        >
          <div class="person-status">
            <div 
              class="status-indicator" 
              :class="{
                'online': person.status === 1, 
                'offline': person.status === 2
              }"
            ></div>
          </div>
          <div class="person-info">
            <span class="person-name">{{ person.name }}</span>
            <span class="person-coords">({{ formatCoord(person.lng) }}, {{ formatCoord(person.lat) }})</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "TaskPeopleDisplay",
  props: {
    // 地图实例
    map: {
      type: Object,
      required: true
    },
    // 人员数据
    taskPeople: {
      type: Array,
      default: () => []
    },
    // 是否显示信息面板
    showInfoPanel: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      markers: [], // 人员标记数组
      moveIntervals: [], // 运动定时器数组
      activePersonIndex: -1, // 当前选中的人员索引
      personIcons: {
        status1: null, // status=1 的图标（绿色）
        status2: null  // status=2 的图标（红色）
      },
      infoWindows: [], // 信息窗口数组
      openInfoWindows: new Set() // 记录打开的信息窗口索引
    };
  },
  computed: {
    // 展平人员数据（处理二维数组）
    flattenedPeople() {
      const result = [];
      this.taskPeople.forEach(group => {
        if (Array.isArray(group)) {
          group.forEach(person => {
            if (person && person.name) {
              result.push(person);
            }
          });
        }
      });
      return result;
    }
  },
  watch: {
    // 监听人员数据变化
    taskPeople: {
      handler() {
        this.updatePeopleMarkers();
      },
      deep: true
    }
  },
  mounted() {
    this.initPersonIcons();
    this.updatePeopleMarkers();
  },
  beforeDestroy() {
    this.clearAllMarkers();
    this.clearAllIntervals();
    this.closeAllInfoWindows();
  },
  methods: {
    // 初始化人员图标
    initPersonIcons() {
      // 创建status=1的图标（绿色）
      this.personIcons.status1 = new AMap.Icon({
        size: new AMap.Size(32, 32),
        image: require('@/assets/green.png'), // 绿色图标
        imageSize: new AMap.Size(32, 32)
      });
      
      // 创建status=2的图标（红色）
      this.personIcons.status2 = new AMap.Icon({
        size: new AMap.Size(32, 32),
        image: require('@/assets/red1.png'), // 红色图标
        imageSize: new AMap.Size(32, 32)
      });
    },
    
    // 根据status获取对应图标
    getPersonIconByStatus(status) {
      switch(status) {
        case 1:
          return this.personIcons.status1;
        case 2:
          return this.personIcons.status2;
        default:
          return this.personIcons.status2; // 默认使用红色图标
      }
    },
    
    // 更新人员标记
    updatePeopleMarkers() {
      // 清除现有标记和定时器
      this.clearAllMarkers();
      this.clearAllIntervals();
      
      // 为每个人员创建标记
      this.flattenedPeople.forEach((person, index) => {
        if (person.lng && person.lat) {
          this.createPersonMarker(person, index);
        }
      });
    },
    
    // 创建人员标记
    createPersonMarker(person, index) {
      // 根据status获取对应图标
      const icon = this.getPersonIconByStatus(person.status);
      
      // 创建标记
      const marker = new AMap.Marker({
        position: [parseFloat(person.lng), parseFloat(person.lat)],
        title: `${person.name} (${person.status === 1 ? '在线' : '离线'})`,
        icon: icon,
        offset: new AMap.Pixel(-16, -32),
        extData: {
          personIndex: index
        }
      });
      
      // 添加标签
      marker.setLabel({
        content: `<div class="person-label">${person.name}</div>`,
        offset: new AMap.Pixel(0, 0),
        direction: 'top'
      });
      
      // 添加到地图
      marker.setMap(this.map);
      
      // 添加点击事件
      marker.on('click', () => {
        this.onPersonClick(person, index);
      });
      
      // 保存标记引用
      this.markers.push(marker);
      
      // 创建对应的信息窗口
    //   const infoWindow = new AMap.InfoWindow({
    //     content: this.createInfoWindowContent(person, index),
    //     offset: new AMap.Pixel(0, -30)
    //   });
      
      // 保存信息窗口引用
    //   this.infoWindows.push(infoWindow);
      
      // 开始随机运动（2秒后开始）
    //   this.startRandomMovement(marker, person, index, infoWindow);
      this.startRandomMovement(marker, person, index);
    },
    
    // 创建信息窗口内容
    createInfoWindowContent(person, index) {
      const statusText = person.status === 1 ? '在线' : (person.status === 2 ? '离线' : '未知');
      const statusClass = person.status === 1 ? 'status-online' : (person.status === 2 ? 'status-offline' : 'status-unknown');
      
      return `
        <div class="person-info-window" id="info-window-${index}">
          <h4>${person.name}</h4>
          <p>经度: ${person.lng}</p>
          <p>纬度: ${person.lat}</p>
          <p>状态: <span class="${statusClass}">${statusText}</span></p>
          <button class="close-info-btn" onclick="window.closeInfoWindow(${index})">关闭</button>
        </div>
      `;
    },
    
    // 开始随机运动
    startRandomMovement(marker, person, index, infoWindow) {
      // 2秒后开始随机运动
      const timeout = setTimeout(() => {
        const interval = setInterval(() => {
          // 生成随机偏移量
          const offsetLng = (Math.random() - 0.5) * 0.001;
          const offsetLat = (Math.random() - 0.5) * 0.001;
          
          // 更新人员坐标
          const newLng = parseFloat(person.lng) + offsetLng;
          const newLat = parseFloat(person.lat) + offsetLat;
          
          // 更新人员数据
          person.lng = newLng.toFixed(6);
          person.lat = newLat.toFixed(6);
          
          // 更新标记位置
          marker.setPosition([newLng, newLat]);
          
          // 如果信息窗口是打开状态，则跟随移动
        //   if (this.openInfoWindows.has(index)) {
        //     // 先更新位置再更新内容，确保位置正确
        //     infoWindow.setPosition([newLng, newLat]);
        //     // 更新信息窗口内容
        //     infoWindow.setContent(this.createInfoWindowContent(person, index));
        //   }
          
          // 触发位置更新事件
          this.$emit('person-position-updated', {
            person: person,
            index: index,
            position: [newLng, newLat]
          });
        }, 2000); // 每2秒移动一次
        
        this.moveIntervals.push(interval);
      }, 2000);
      
      this.moveIntervals.push(timeout);
    },
    
    // 清除所有标记
    clearAllMarkers() {
      this.markers.forEach(marker => {
        marker.setMap(null);
      });
      this.markers = [];
    },
    
    // 清除所有定时器
    clearAllIntervals() {
      this.moveIntervals.forEach(timer => {
        if (typeof timer === 'number') {
          clearTimeout(timer);
        } else if (timer && typeof timer.clearInterval === 'function') {
          timer.clearInterval();
        }
      });
      this.moveIntervals = [];
    },
    
    // 关闭所有信息窗口
    closeAllInfoWindows() {
      this.infoWindows.forEach(infoWindow => {
        if (infoWindow.getIsOpen()) {
          infoWindow.close();
        }
      });
      this.openInfoWindows.clear();
    },
    
    // 关闭指定索引的信息窗口
    closeInfoWindow(index) {
      const infoWindow = this.infoWindows[index];
      if (infoWindow && infoWindow.getIsOpen()) {
        infoWindow.close();
        this.openInfoWindows.delete(index);
      }
    },
    
    // 人员点击事件
    onPersonClick(person, index) {
      this.activePersonIndex = index;
      
      // 居中显示该人员
      this.map.setCenter([parseFloat(person.lng), parseFloat(person.lat)]);
      
      // 获取对应的信息窗口
      const infoWindow = this.infoWindows[index];
      if (infoWindow) {
        // 打开信息窗口并确保它跟随标记
        infoWindow.open(this.map, [parseFloat(person.lng), parseFloat(person.lat)]);
        // 记录该信息窗口为打开状态
        this.openInfoWindows.add(index);
      }
      
      // 触发点击事件
      this.$emit('person-click', {
        person: person,
        index: index
      });
    },
    
    // 聚焦到指定人员
    focusOnPerson(person, index) {
      this.map.setCenter([parseFloat(person.lng), parseFloat(person.lat)]);
      this.map.setZoom(18);
    },
    
    // 格式化坐标显示
    formatCoord(coord) {
      if (!coord) return 'N/A';
      return parseFloat(coord).toFixed(4);
    }
  }
};

// 全局函数用于关闭信息窗口
window.closeInfoWindow = function(index) {
  const element = document.querySelector('.task-people-display');
  if (element && element.__vue__) {
    element.__vue__.closeInfoWindow(index);
  }
};
</script>

<style scoped>
.task-people-display {
  position: absolute;
  top: 127px;
  right: 26px;
  z-index: 100;
}

.people-info-panel {
  background: rgba(0, 20, 40, 0.9);
  border: 1px solid #00aaff;
  border-radius: 8px;
  padding: 15px;
  color: #00ccff;
  min-width: 250px;
  max-height: 400px;
  overflow-y: auto;
}

.people-info-panel h3 {
  margin: 0 0 10px 0;
  color: #00aaff;
  font-size: 16px;
}

.people-list {
  max-height: 350px;
  overflow-y: auto;
}

.person-item {
  display: flex;
  align-items: center;
  padding: 8px 10px;
  margin-bottom: 5px;
  background: rgba(0, 50, 100, 0.5);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.person-item:hover {
  background: rgba(0, 100, 200, 0.7);
}

.person-item.active {
  background: rgba(0, 150, 255, 0.8);
  border-left: 3px solid #00ffff;
}

.person-status {
  margin-right: 10px;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  display: inline-block;
}

.status-indicator.online {
  background-color: #00ff00;
  box-shadow: 0 0 10px #00ff00;
  animation: blink-online 1.5s infinite;
}

.status-indicator.offline {
  background-color: #ff0000;
  box-shadow: 0 0 10px #ff0000;
  animation: blink-offline 1.5s infinite;
}

@keyframes blink-online {
  0% { opacity: 1; }
  50% { opacity: 0.3; }
  100% { opacity: 1; }
}

@keyframes blink-offline {
  0% { opacity: 1; }
  50% { opacity: 0.3; }
  100% { opacity: 1; }
}

.person-info {
  flex: 1;
}

.person-name {
  font-weight: bold;
  color: #00ccff;
  display: block;
}

.person-coords {
  font-size: 12px;
  color: #00aaff;
  display: block;
  margin-top: 3px;
}
</style>

<style>
/* 全局样式 */
.person-label {
  background: rgba(0, 100, 200, 0.8);
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
  white-space: nowrap;
  box-shadow: 0 0 5px rgba(0, 200, 255, 0.5);
}

.person-info-window {
  min-width: 180px;
  background: rgba(0, 20, 40, 0.9);
  border: 1px solid #00aaff;
  border-radius: 8px;
  padding: 15px;
  color: #00ccff;
}

.person-info-window h4 {
  margin: 0 0 10px 0;
  color: #0066cc;
}

.person-info-window p {
  margin: 5px 0;
  font-size: 14px;
}

.status-online {
  color: #00ff00;
  font-weight: bold;
}

.status-offline {
  color: #ff0000;
  font-weight: bold;
}

.status-unknown {
  color: #ffff00;
  font-weight: bold;
}

.close-info-btn {
  background: #cc3333;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 3px 8px;
  cursor: pointer;
  font-size: 12px;
  margin-top: 5px;
}

.close-info-btn:hover {
  background: #ff3333;
}

/* 信息窗口样式 */
.amap-info-contentContainer .amap-info-content {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}
</style>